package game.Engine.Server;

import game.MainController;
import game.Engine.Entity.Entity;
import game.Input.GameActionWrapper;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.Vector;

import org.feiteira.network.copy.SeriDataPackage;
import org.feiteira.network.copy.SeriEventHandler;
import org.feiteira.network.copy.SeriServer;

import com.googlecode.cqengine.IndexedCollection;

public class ClientHandler implements SeriEventHandler {
	private IndexedCollection<Entity> entities;
	
	public ClientHandler(){
		entities = MainController.gameEngine.entities;
	}

	@Override
	public void messageArrived(SeriDataPackage pack) {
		Object fromClient = pack.getObject();
		Serializable objectToSend = null;
		if(fromClient instanceof String){//Its requesting an update or closing connection
			if(((String) fromClient).equalsIgnoreCase("Bye")){
				objectToSend = "Bye";
			}else if(((String) fromClient).equalsIgnoreCase("Update")){
				Vector<Entity> toSend = new Vector<Entity>();
				toSend.addAll(entities);
				objectToSend = toSend;
			}else if(((String) fromClient).equalsIgnoreCase("RequestID")){
				objectToSend = "ID"+MainController.getNextSentID();//TODO We need to get the id number
			}
			
			try {
				SeriServer.reply(pack, objectToSend);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}else if(fromClient instanceof Collection<?>){
			for(Object o: (Collection)fromClient){
				if(o instanceof GameActionWrapper){
					GameActionWrapper gaw = (GameActionWrapper)o;
					if(gaw.getSource() < MainController.gameEngine.buffers.size()){
						MainController.gameEngine.buffers.get(gaw.getSource()).add(gaw);
					}
				}
			}
		}
		
		
	}

	@Override
	public void shutdownCompleted() {
		
	}
}